package com.jt.www.admin.user.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jt.www.admin.user.service.BranchOfficeService;
import com.jt.www.dao.mapper.branchOffice.BranchOfficeMapper;
import com.jt.www.model.entity.branchOffice.BranchOfficeEntity;
import com.jt.www.model.param.branchOffice.BranchOfficeParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
//@SuppressWarnings("unchecked")
public class BranchOfficeServiceImpl implements BranchOfficeService {
    private static final String PROVINCE = "province";
    private static final String IS_DELETED = "isDeleted";
    private static final String TOTAL = "全国";
    private static final String ID = "id";

    @Autowired
    private BranchOfficeMapper mapper;

    @Override
    public List<String> getProvinces() {
        Weekend<BranchOfficeEntity> weekend = new Weekend<>(BranchOfficeEntity.class);
        WeekendCriteria<BranchOfficeEntity, Object> criteria = weekend.weekendCriteria();
        criteria.andEqualTo(IS_DELETED, false);
        weekend.orderBy(ID);
        List<BranchOfficeEntity> entities = mapper.selectByExample(weekend);

        List<String> result = new ArrayList<String>(40);
        result.add(0, TOTAL);

        result.addAll(entities.stream()
                .map(BranchOfficeEntity::getProvince)
                .distinct()
                .collect(Collectors.toList()));

        return result;
    }

    @Override
    public PageInfo getList(BranchOfficeParam param) {
        String province = param.getProvince();
        Weekend<BranchOfficeEntity> weekend = new Weekend<>(BranchOfficeEntity.class);
        WeekendCriteria<BranchOfficeEntity, Object> criteria = weekend.weekendCriteria();
        criteria.andEqualTo(IS_DELETED, false);
        if (province == null || TOTAL.equals(province)) {
            criteria.andIsNotNull(PROVINCE);
        } else {
            criteria.andEqualTo(PROVINCE, province);
        }
        weekend.orderBy(ID);

        Page page = PageHelper.startPage(param.getPn(), param.getPs());
        List<BranchOfficeEntity> entities = mapper.selectByExample(weekend);
        PageInfo info = new PageInfo(page);
        info.setList(entities);
        return info;
    }
}
